#sudo docker run --restart unless-stopped -v /home/orangepi/Desktop:/home --device=/dev/video1:/dev/video1  cd98831865c3 python3 /home/picture.py
import cv2
import numpy as np
import time
import os
import sys
from dashscope import MultiModalConversation
import subprocess
from typing import Tuple

# 配置参数
CAMERA_DEVICE = "/dev/video1"
RESOLUTION = (480, 320)
MIN_AREA = 20000
ITER = 5
CHECK_INTERVAL = 0.2  # 检测间隔（秒）
API_KEY = 'sk-d4 30c72e49082'  # 替换为你的API密钥

def analyze_image(image_path):
    """调用阿里云大模型分析图片"""
    messages = [{
        "role": "system",
        "content": [{"text": "You are a helpful assistant."}]
    },{
        'role':'user',
        'content': [
            {'image': f"file://{os.path.abspath(image_path)}"},
            {'text': '画面中是否有人。回答格式严格使用：是 或 否'}
        ]
    }]
    
    try:
        response = MultiModalConversation.call(
            api_key=API_KEY,
            model='qwen2.5-vl-3b-instruct',
            messages=messages
        )
        return response["output"]["choices"][0]["message"].content[0]["text"]
    except Exception as e:
        print(f"API调用失败: {str(e)}")
        return "分析失败"

def ssh_exec_command(
    host: str = "172.17.0.1",
    user: str = "orangepi",
    password: str = "orangepi",
    command: str = "ls",
    timeout: int = 5
) -> tuple:
    """SSH远程执行命令"""
    try:
        ssh_cmd = [
            "sshpass", "-p", password,
            "ssh",
            "-o", "StrictHostKeyChecking=no",
            "-o", "ConnectTimeout=3",
            f"{user}@{host}",
            command
        ]
        
        result = subprocess.run(
            ssh_cmd,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            timeout=timeout
        )
        return (True, result.stdout.decode().strip())
    except subprocess.CalledProcessError as e:
        return (False, f"Command failed: {e.stderr.decode()}")
    except subprocess.TimeoutExpired:
        return (False, "Connection timeout")
    except Exception as e:
        return (False, f"Unexpected error: {str(e)}")

def handle_result(result):
    """处理分析结果并执行对应操作（新版适配车头/车尾）"""
    # 移除所有逗号分割逻辑，直接判断结果值
    if result == "是":
        command = "gpio mode 0 out ; gpio write 0 0 ; sleep 0.1 ; gpio write 0 1"
    elif result == "否":
        command = "gpio mode 1 out ; gpio write 1 0 ; sleep 0.1 ; gpio write 1 1"
    else:
        print(f"未知结果类型: {result}")
        return

    # 统一执行命令
    success, output = ssh_exec_command(command=command)
    print(f"【{result}】操作: 成功={success}, 输出={output}")

def run_camera():
    """运行摄像头监控模式"""
    cap = cv2.VideoCapture(CAMERA_DEVICE, cv2.CAP_V4L2)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

    # 初始化背景
    ret, background = cap.read()
    if not ret:
        print("无法读取摄像头")
        exit()
    background = cv2.resize(background, RESOLUTION)
    background_gray = cv2.cvtColor(background, cv2.COLOR_BGR2GRAY)
    background_gray = cv2.GaussianBlur(background_gray, (21, 21), 0)

    last_check = time.time()

    try:
        while True:
            current_time = time.time()
            if current_time - last_check >= CHECK_INTERVAL:
                # 清空缓冲区
                for _ in range(10):  # 丢弃前3帧（根据摄像头调整次数）
                    cap.grab()
                
                # 读取最新帧
                ret, frame = cap.read()
                if not ret:
                    continue
                
                # 运动检测处理
                frame_resized = cv2.resize(frame, RESOLUTION)
                gray = cv2.cvtColor(frame_resized, cv2.COLOR_BGR2GRAY)
                gray = cv2.GaussianBlur(gray, (21, 21), 0)
                
                diff = cv2.absdiff(background_gray, gray)
                _, thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)
                thresh = cv2.dilate(thresh, None, iterations=ITER)
                
                contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
                #print(contours)
                if any(cv2.contourArea(c) > MIN_AREA for c in contours):
                    # 新增代码：计算并打印最大轮廓面积
                    large_contours = [c for c in contours if cv2.contourArea(c) > MIN_AREA]
                    if large_contours:
                        largest_contour = max(large_contours, key=cv2.contourArea)
                        max_area = cv2.contourArea(largest_contour)
                        print(f"最大有效轮廓面积：{max_area} 像素（阈值：{MIN_AREA}）")
                      
                    filename = f"picture/motion_{time.strftime('%Y%m%d_%H%M%S')}.jpg"
                    cv2.imwrite(filename, frame_resized)
                    print(f"检测到变化，已保存: {filename}")
                    #time.sleep(3)
                    
                    result = analyze_image(filename)
                    print(f"分析结果: {result}")
                    handle_result(result)
                    background_gray = gray.copy()  # 更新背景

                last_check = current_time
            time.sleep(0.05)
    finally:
        cap.release()

if __name__ == "__main__":
    if len(sys.argv) > 1:
        image_path = sys.argv[1]
        if not os.path.exists(image_path):
            print(f"文件不存在: {image_path}")
            sys.exit(1)
            
        result = analyze_image(image_path)
        print(f"分析结果: {result}")
        handle_result(result)
    else:
        if not os.path.exists("picture"):
            os.makedirs("picture", exist_ok=True)
        run_camera()